<template>
  <div class="header-container">
    <div class="logo">
      <router-link to="/">
        <h1>爪印</h1>
      </router-link>
    </div>
    <div class="nav-menu">
      <el-menu
        mode="horizontal"
        :ellipsis="false"
        :default-active="activeMenu"
        router
      >
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/pet/list">宠物列表</el-menu-item>
<!--        <el-menu-item index="/pet/adoption">待领养</el-menu-item>-->
        <el-menu-item index="/about">关于我们</el-menu-item>
      </el-menu>
    </div>
    <div class="user-info">
      <template v-if="isLogin">
        <el-dropdown @command="handleCommand">
          <span class="user-dropdown-link">
            <el-avatar :size="32" :src="userInfo.avatar"></el-avatar>
            <span class="username">{{ userInfo.name }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
<!--              <el-dropdown-item command="profile">个人中心</el-dropdown-item>-->
              <el-dropdown-item command="adoptions">我的领养</el-dropdown-item>
<!--              <el-dropdown-item command="favorites">我的收藏</el-dropdown-item>-->
              <el-dropdown-item divided command="logout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <template v-else>
        <router-link to="/login" class="login-btn">
          <el-button type="primary">登录</el-button>
        </router-link>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";

const store = useStore();
const router = useRouter();
const route = useRoute();

// 当前激活的菜单
const activeMenu = computed(() => {
  return route.path;
});

// 是否已登录
const isLogin = computed(() => {
  return !!getToken() || !!localStorage.getItem("isLogin");
});

// 用户信息
const userInfo = computed(() => {
  return {
    name: store.state.name || localStorage.getItem("username") || "用户",
    avatar: store.state.avatar || "",
  };
});

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case "profile":
      router.push("/user/profile");
      break;
    case "adoptions":
      router.push("/user/adoptions");
      break;
    case "favorites":
      router.push("/user/favorites");
      break;
    case "logout":
      logout();
      break;
  }
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm("确定要退出登录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (getToken()) {
        // 调用vuex的退出方法
        store
          .dispatch("LogOut")
          .then(() => {
            router.push("/login");
          })
          .catch(() => {
            // 退出失败，降级处理
            localStorage.removeItem("isLogin");
            localStorage.removeItem("username");
            localStorage.removeItem("userId");
            router.push("/login");
          });
      } else {
        // 使用本地存储模拟的登录状态
        localStorage.removeItem("isLogin");
        localStorage.removeItem("username");
        localStorage.removeItem("userId");
        router.push("/login");
      }
      ElMessage.success("退出成功");
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 组件挂载时，如果已登录但没有用户信息，则获取用户信息
onMounted(() => {
  if (isLogin.value && !userInfo.value.name && getToken()) {
    store.dispatch("GetInfo").catch((error) => {
      console.error("获取用户信息失败:", error);
    });
  }
});
</script>

<style scoped>
.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo {
  margin-right: 20px;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  letter-spacing: 1px;
}

.logo a {
  text-decoration: none;
}

.nav-menu {
  flex: 1;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  font-size: 14px;
  color: #606266;
}

.login-btn {
  text-decoration: none;
}
</style>
